package com.yc.store.servlet;

import com.google.gson.Gson;
import com.yc.store.bean.Bill;
import com.yc.store.bean.BillItem;
import com.yc.store.bean.Goods;
import com.yc.store.bean.Result;
import com.yc.store.biz.BillBIz;
import com.yc.store.biz.BizExeption;
import com.yc.store.biz.GoodsBiz;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/4/25
 * Email haijunzhou@hnit.edu.cn
 */
@WebServlet("/addBill")
public class AddBillServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Bill bill = new Bill();
        // type, custom, TODO uid=1 (当前用户, 现在没有登录)
        // gid 数组, num 数组, price 数组
        bill.setType(req.getParameter("type"));
        bill.setCustom(req.getParameter("custom"));
        bill.setSums(Double.valueOf(req.getParameter("sums")));
        bill.setUid(Integer.valueOf(req.getParameter("uid")));
        String[] gids = req.getParameterValues("gid");
        String[] nums = req.getParameterValues("num");
        String[] pris = req.getParameterValues("price");
        // 创建 items 集合
        bill.setItems( new ArrayList<>());
        for (int i = 0; i < gids.length; i++) {
            BillItem bi = new BillItem();
            bi.setGid(Integer.valueOf(gids[i]));
            bi.setNum(Integer.valueOf(nums[i]));
            bi.setPrice(Double.valueOf(pris[i]));
            // 添加到 items 集合中
            bill.getItems().add(bi);
        }

        WebApplicationContext ioc=
                WebApplicationContextUtils.getWebApplicationContext(req.getServletContext());
        BillBIz billBIz = ioc.getBean(BillBIz.class);
        Result result;
        try {
            billBIz.addBill(bill);
            result = new Result(1,"添加订单成功！",bill);
        } catch (BizExeption e) {
            result = new Result(0,e.getMessage(),bill);
        }

        resp.setContentType("application/json;charset=utf-8");
        Gson gson = new Gson();
        String json = gson.toJson(result);
        resp.getWriter().append(json);
    }
}
